﻿using System;
using System.Collections.Generic;
using System.Linq;

namespace EnterpriseLibraryExtensions.Services.Mapping
{
    internal class EntityTranslatorCollectionStrategyFactory : IEntityTranslatorCollectionStrategyFactory
    {
        public ICollectionHandler CreateCollectionHandler(Type targetType, object sourceInstance)
        {
            if (targetType.IsArray)
            {
                int count = ((IEnumerable<object>)sourceInstance).Count();
                return new ArrayCollectionHandler(targetType.GetElementType(), count);
            }
            
            if (targetType.IsGenericType && targetType.GetGenericTypeDefinition() == typeof(List<>))
            {
                return new ListCollectionHandler(targetType.GetGenericArguments()[0]);
            }

            if (targetType.IsGenericType && targetType.GetGenericTypeDefinition() == typeof(IEnumerable<>))
            {
                return new ListCollectionHandler(targetType.GetGenericArguments()[0]);
            }

            return null;
        }
    }
}
